import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {PersonalService} from "../services/personal.service";
import {PageSubject} from "../util/page-subject";
import {Me} from "./me";
import {ResponseUtil} from "../util/response-util";
import {MsgResult} from "../models/msg-result";
import {MsgConstants} from "../constants/constants";
import {OneDialogService} from "../widgets/one-dialog/one-dialog.service";
import {Router, ActivatedRoute} from "@angular/router";

@Component({
  selector: 'app-me',
  templateUrl: './me.component.html'
})
export class MeComponent implements OnInit {

  meInfo: Me;

  meInfoForm: FormGroup;

  updatePwdForm: FormGroup;

  constructor(private router: Router,
              private route: ActivatedRoute,
              private fb: FormBuilder,
              private pageSubject: PageSubject,
              private responseUtil: ResponseUtil,
              private dialogService: OneDialogService,
              private personalService: PersonalService) {
    this.initObject();
  }

  ngOnInit() {
    this.pushPage();
    this.initLoginUser();
  }

  /**
   * 面包屑导航
   */
  pushPage() {
    this.pageSubject.pushPage("个人中心", "");
  }

  /**
   * 实例化对象
   */
  private initObject() {
    this.meInfo = new Me();
    this.buildInfoForm();
    this.buildForm();
  }

  /**
   * 构造用户信息表单
   */
  buildInfoForm(): void {
    this.meInfoForm = this.fb.group({
      'userName': [this.meInfo.userName = ""],
      'regionId': [this.meInfo.regionId = ""],
      'regionName': [this.meInfo.regionName = ""],
      'orgId': [this.meInfo.orgId = ""],
      'orgName': [this.meInfo.orgName = ""],
      'depId': [this.meInfo.depId = ""],
      'depName': [this.meInfo.depName = ""],
      'phone': [this.meInfo.phone = ""],
      'type': [this.meInfo.type = ""],
      'duty': [this.meInfo.duty = "", [
        Validators.maxLength(15),
      ]]
    });
  }


  initLoginUser() {
    this.personalService.getPersonalInfo().subscribe(
      result => this.responseUtil.success(result, this.processLoginResult),
      error => this.responseUtil.error(error)
    );
  }

  private processLoginResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.meInfo.userName = result.data.userCode;
      this.meInfo.duty = result.data.duty;
      this.meInfo.phone = result.data.phone;
      this.meInfo.regionName = result.data.regionName;
      this.meInfo.orgName = result.data.orgName;
      this.meInfo.depName = result.data.deptName;
      this.updatePwdForm.patchValue(this.meInfo);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  savePersonalPw() {
    this.meInfo = this.updatePwdForm.value;
    if (this.meInfo.newPassword != this.meInfo.password && this.meInfo.newPassword == this.meInfo.confirmPassword) {
      this.personalService.editPersonalPwd(this.meInfo).subscribe(
        result => this.responseUtil.success(result, this.processUpdatePwdResult),
        message => this.responseUtil.error(message)
      );
    } else {
      if (this.meInfo.password == this.meInfo.newPassword) {
        this.dialogService.modalInfo("新密码与原密码一致！");
      }
      if (this.meInfo.confirmPassword != this.meInfo.newPassword) {
        this.dialogService.modalInfo("新密码与确认密码不一致！");
      }
    }
  }


  /**
   * 密码修改成功处理
   * @param result
   */
  private processUpdatePwdResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.dialogService.modalSuccess("密码修改成功！", () => this.UpdatePwOk());
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  UpdatePwOk = () => {
    this.meInfo.password = "";
    this.meInfo.newPassword = "";
    this.meInfo.confirmPassword = "";
    this.updatePwdForm.patchValue(this.meInfo);
    this.buildForm();
  }


  /**
   * 构造表单
   */
  buildForm(): void {
    this.updatePwdForm = this.fb.group({
      'meId': [this.meInfo.meId],
      'userName': [this.meInfo.userName, [
        Validators.required,
        Validators.maxLength(10),
        Validators.pattern(/^[A-Za-z0-9_]+$/)
      ]],
      'password': [this.meInfo.password, [
        Validators.required,
        Validators.minLength(6),
        Validators.maxLength(20),
        Validators.pattern(/^([a-z_A-Z-.+0-9]+)$/)
      ]],
      'confirmPassword': [this.meInfo.confirmPassword, [
        Validators.required,
        Validators.minLength(6),
        Validators.maxLength(16),
        Validators.pattern(/^([a-z_A-Z-.+0-9]+)$/)
      ]],
      'newPassword': [this.meInfo.confirmPassword, [
        Validators.required,
        Validators.minLength(6),
        Validators.maxLength(16),
        Validators.pattern(/^([a-z_A-Z-.+0-9]+)$/)
      ]]
    });

    this.updatePwdForm.valueChanges.subscribe(
      data => this.onValueChanged(data)
    );
    this.onValueChanged();
  }

  /**
   * 值变化监听
   * @param data
   */
  onValueChanged(data?: any) {
    if (!this.updatePwdForm) {
      return;
    }
    const form = this.updatePwdForm;
    for (const field in this.formErrors) {
      this.formErrors[field] = '';
      const control = form.get(field);
      if (control && control.dirty && !control.valid) {
        const messages = this.validationMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + ' ';
        }
      }
    }
  }

  /**
   * 校验字段
   * @type {{name: string; code: string}}
   */
  formErrors = {
    'userName': '',
    'password': '',
    'confirmPassword': '',
    'newPassword': '',
  };

  /**
   * 校验提示信息
   * @type {{name: {required: string; maxlength: string}; code: {required: string; maxlength: string; pattern: string}}}
   */
  validationMessages = {
    'userName': {
      'required': '用户不能为空',
      'maxlength': '长度不能超过10',
      'pattern': '只能由字母、数字、下划线组成'
    },
    'password': {
      'required': '密码不能为空',
      'minlength': '长度不能少于6',
      'maxlength': '长度不能超过20',
      'pattern': '只能由字母，数字，下划线，横线，加号及点组成'
    },
    'confirmPassword': {
      'required': '确认密码不能为空',
      'minlength': '长度不能少于6',
      'maxlength': '长度不能超过16',
      'pattern': '只能由字母，数字，下划线，横线，加号及点组成'
    },
    'newPassword': {
      'required': '确认密码不能为空',
      'minlength': '长度不能少于6',
      'maxlength': '长度不能超过16',
      'pattern': '只能由字母，数字，下划线，横线，加号及点组成'
    }
  };
}
